package mp

import (
	"context"
	"errors"

	"ruikc.com/server/api/internal/db"
	"ruikc.com/server/api/internal/svc"
	"ruikc.com/server/api/internal/types"
	"ruikc.com/server/models"
	"ruikc.com/server/utils"
	xb "xorm.io/builder"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeptDeleteLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDeptDeleteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeptDeleteLogic {
	return &DeptDeleteLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeptDeleteLogic) DeptDelete(req *types.IdJson) (resp string, err error) {
	has := db.ExistData(&models.Dept{
		Pid: req.Id,
	})
	if has {
		return "", errors.New("存在子部门，无法删除")
	}
	has = db.ExistWhereData(&models.User{}, xb.Like{"dept_tier", "'%," + utils.IntToString(req.Id) + ",%'"})
	if has {
		return "", errors.New("部门下有用户，无法删除")
	}
	dept := &models.Dept{
		Id: req.Id,
	}
	db.DeleteData(dept)

	return "操作成功", nil
}
